//
//  AppDelegate.m
//  PaiLeXiongProject
//
//  Created by 小獾科技 on 2017/8/15.
//  Copyright © 2017年 小獾科技. All rights reserved.
//

#import "AppDelegate.h"
#import "RootViewController.h"
#import "LoginViewController.h"
#import "AdvertisingViewController.h"
#import <AlipaySDK/AlipaySDK.h>
#import <CoreLocation/CoreLocation.h>
#import "WXApi.h"
#import "ShareView.h"
#import "GW_Request.h"
#import "JPUSHService.h"

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
@interface AppDelegate ()<CLLocationManagerDelegate,JPUSHRegisterDelegate>
@property (nonatomic, strong) CLLocationManager* locationManager;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    NSLog(@"屏幕大小 %f %f", GWIDTH, GHEIGHT);
    application.applicationIconBadgeNumber = 0;
    [GW_Tool versionCheck];
    [GW_Request sharedInstance];
    
    //微信注册
    [WXApi registerApp:kWeiXinId];
    
    [self startLocation];//定位
    [GW_Tool configAppStyle];
    [self setRootVC];
    [self.window makeKeyAndVisible];
    self.window.backgroundColor = ColorWhite;
    Advertising_ViewController *adVC = [Advertising_ViewController new];
    adVC.view.frame = CGRectMake(0, 0, GWIDTH, GHEIGHT);
    [self.window addSubview:adVC.view];
    
    
    [self jPushRegister];
    
//    [JPUSHService setupWithOption:launchOptions appKey:@"7eca0b365591a9d1460781c5"
//                          channel:@"app stroe"
//                 apsForProduction:NO  // 0 (默认值)表示采用的是开发证书，1 表示采用生产证书发布应用
//            advertisingIdentifier:nil];
    
    [JPUSHService setupWithOption:launchOptions appKey:@"7eca0b365591a9d1460781c5" channel:@"app store" apsForProduction:YES]; // apsForProduction 0 false NO (默认值)表示采用的是开发证书，测试版 1 ture YES 表示采用生产证书发布应用，线上版
    
    return YES;
}

- (void)jPushRegister
{
    //Required  激光推送
    //notice: 3.0.0及以后版本注册可以这样写，也可以继续用之前的注册方式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
}

- (void)startLocation
{
    //    检测定位功能是否开启
        if([CLLocationManager locationServicesEnabled]){
    
                self.locationManager = [[CLLocationManager alloc] init];
    
                if([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]){
                    [self.locationManager requestWhenInUseAuthorization];
                    [self.locationManager requestAlwaysAuthorization];
    
                //设置代理
                [self.locationManager setDelegate:self];
                //设置定位精度
                [self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
                //设置距离筛选
                [self.locationManager setDistanceFilter:100];
                //开始定位
                [self.locationManager startUpdatingLocation];
                //设置开始识别方向
    //            [self.locationManager startUpdatingHeading];
            }
            else{
                AlertViewManager *alert = [[AlertViewManager alloc] initWithTitle:nil message:@"您还没有开启定位" cancelButtonTitle:@"确定" confirmButtonTitle:nil delegate:nil block:^(NSInteger idx) {
                    
                }];
                [alert show];
            }
        }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    CLLocation *newLocation = locations[0];//获取到的最新的经纬度
    
    CLLocationCoordinate2D oldCoordinate = newLocation.coordinate;
    
    NSLog(@"旧的经度：%f,旧的纬度：%f",oldCoordinate.longitude,oldCoordinate.latitude);
    
    NSString *lon = [NSString stringWithFormat:@"%f", oldCoordinate.longitude];
    NSString *lat = [NSString stringWithFormat:@"%f", oldCoordinate.latitude];
    [[NSUserDefaults standardUserDefaults] setObject:lon forKey:@"long"];
    [[NSUserDefaults standardUserDefaults] setObject:lat forKey:@"lat"];
    [manager stopUpdatingLocation];
    
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    
    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        for (CLPlacemark *place in placemarks) {
            
                        NSLog(@"name,%@",place.name);                       // 位置名
            
                        NSLog(@"thoroughfare,%@",place.thoroughfare);       // 街道
            
                        NSLog(@"subThoroughfare,%@",place.subThoroughfare); // 子街道
            
                        NSLog(@"locality,%@",place.locality);               // 市
            
                        NSLog(@"subLocality,%@",place.subLocality);         // 区
            
                        NSLog(@"country,%@",place.country);// 国家
            
            [[NSUserDefaults standardUserDefaults] setObject:place.locality forKey:kCityName];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
    }];
}

- (void)setRootVC
{

    RootViewController *rootVC = [[RootViewController alloc] init];
    self.window.rootViewController = rootVC;
}

- (void)setAdvertisingView
{
    // 广告运营位
    Advertising_ViewController *adVC = [Advertising_ViewController new];
    adVC.view.frame = CGRectMake(0, 0, GWIDTH, GHEIGHT);
    [self.window addSubview:adVC.view];
}

//微信所用
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    if ([url.absoluteString hasPrefix:kWeiXinId]) {
        return [WXApi handleOpenURL:url delegate:[ShareView sharedInstance]];
    }
    return YES;
}


- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    
    if([url.host isEqualToString:@"safepay"])
    {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result:%@", resultDic);
        }];
        
        // 授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            // 解析 auth code
            NSString *result = resultDic[@"result"];
            NSString *authCode = nil;
            if (result.length>0) {
                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                for (NSString *subResult in resultArr) {
                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                        authCode = [subResult substringFromIndex:10];
                        break;
                    }
                }
            }
            NSLog(@"授权结果 authCode = %@", authCode?:@"");
        }];
    }
    
    NSString *stringWeiXinShare = [NSString stringWithFormat:@"%@://platformId=wechat", kWeiXinId];
    NSString *stringWeiXinOauth = [NSString stringWithFormat:@"%@://oauth", kWeiXinId];
    NSString *stringWeiXinPay = [NSString stringWithFormat:@"%@://pay/",kWeiXinId];
    
    NSString *urlPath = url.absoluteString;
    if([urlPath hasPrefix:stringWeiXinShare]) {
        
        // 微信分享回调
        return [WXApi handleOpenURL:url delegate:[ShareView sharedInstance]];
        
        
    } else if([urlPath hasPrefix:stringWeiXinOauth]) {
        
        // 微信登录
        return [WXApi handleOpenURL:url delegate:[ShareView sharedInstance]];
        
        
    } else if([urlPath hasPrefix:stringWeiXinPay]) {
        
        // 微信支付
        return [WXApi handleOpenURL:url delegate:[ShareView sharedInstance]];
        
        
    }
    return YES;
}
// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
        
        // 授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            // 解析 auth code
            NSString *result = resultDic[@"result"];
            NSString *authCode = nil;
            if (result.length>0) {
                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                for (NSString *subResult in resultArr) {
                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                        authCode = [subResult substringFromIndex:10];
                        break;
                    }
                }
            }
            NSLog(@"授权结果 authCode = %@", authCode?:@"");
        }];
    }
    
    
    NSString *stringWeiXinShare = [NSString stringWithFormat:@"%@://platformId=wechat", kWeiXinId];
    NSString *stringWeiXinOauth = [NSString stringWithFormat:@"%@://oauth", kWeiXinId];
    NSString *stringWeiXinPay = [NSString stringWithFormat:@"%@://pay/",kWeiXinId];
    
    NSString *urlPath = url.absoluteString;
    if([urlPath hasPrefix:stringWeiXinShare]) {
        
        // 微信分享回调
        return [WXApi handleOpenURL:url delegate:[ShareView sharedInstance]];
        
        
    } else if([urlPath hasPrefix:stringWeiXinOauth]) {
        
        // 微信登录
        return [WXApi handleOpenURL:url delegate:[ShareView sharedInstance]];
        
        
    } else if([urlPath hasPrefix:stringWeiXinPay]) {
        
        // 微信支付
        return [WXApi handleOpenURL:url delegate:[ShareView sharedInstance]];
        
        
    }
    return YES;
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    /// Required - 注册 DeviceToken

    [JPUSHService registerDeviceToken:deviceToken];
}
//失败
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

#pragma mark- JPUSHRegisterDelegate

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary *userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
    NSLog(@"推送 10 ");
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    NSLog(@"推送 7 ");
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    NSLog(@"推送 6 ");
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];//设置桌面图标消息个数为0
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
